/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年03月03日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>

using namespace std;


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if( head == NULL )
            return NULL;

        ListNode newhead = ListNode(0);
        newhead.next = head;
        ListNode *p1 = &newhead;

        while( p1->next && p1->next->val < x ){
            p1 = p1->next;
        }

        ListNode *p2 = p1;
        ListNode *tmp = NULL;
        while( p2->next ){
            if( p2->next->val < x ){
                tmp = p1->next;
                p1->next = p2->next;
                p2->next = p2->next->next;
                p1->next->next = tmp;
                p1 = p1->next;
            }else{
                p2 = p2->next;
            }
        }

        return newhead.next;
    }
};


class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode node1 = ListNode(0);
        ListNode node2 = ListNode(1);

        ListNode *p1 = &node1;
        ListNode *p2 = &node2;
        ListNode *tmp = head;
        while( head ){
            if( head->val < x ){
                p1->next = head;
                p1 = p1->next;
            }else{
                p2->next = head;
                p2 = p2->next;
            }

            head = head->next;
        }

        p2->next = NULL;
        p1->next = node2.next;

        return node1.next;
    }
};

